import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Dropdown, Menu, Icon, Popconfirm, message, Modal, Select, Tree, TreeSelect } from 'antd'
import _ from 'lodash'

import Ajax from 'lib/Ajax'
import { getNewTreeData, findRowData, addRowData, removeRowData, confirmDelete } from 'lib/fun'
import SelectOrg from './selectOrg'

const FormItem = Form.Item;
const TreeNode = Tree.TreeNode;
const SelectTreeNode = TreeSelect.TreeNode;

class ModuleName extends Component {
	constructor(props) {
    super(props);
    const value = this.props.value || {};
    this.state = {
      visible: false,
      value: value,
      toSelected: {}
    }
  }

  componentDidMount() {
    
  }

  componentWillReceiveProps(nextProps) {
    // Should be a controlled component.
    if ('value' in nextProps) {
      const value = nextProps.value;
      this.setState({
        value: value
      });
    }
  }

  onOk = ()=>{
    if(_.isObject(this.state.toSelected)&&this.state.toSelected.orgName){
      this.setState({
        visible: false,
        value: this.state.toSelected
      });
    }else{
      this.setState({
        visible: false,
        value: this.state.value||{}
      });
    }
    this.triggerChange(this.state.toSelected||{});
  }

  triggerChange = () => {
    // Should provide an event to pass value to Form.
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(this.state.toSelected);
    }
  }

  onCancel = ()=>{
    this.setState({
      visible: false
    });
  }

  handleSelect = (selected)=>{
    this.setState({
      toSelected: selected
    });
  }

  selectOrg = ()=>{
    this.setState({
      visible: true
    });
  }

  render() {
    const { visible } = this.state;
    console.log('value', _.isObject(this.state.value)&&this.state.value.orgName?this.state.value.orgName:this.state.value)
    return (
    	<div>
        <Input 
          value={ this.state.value.orgName||""} 
          onChange={ this.triggerChange } 
          onClick={ this.selectOrg }
        />
        <Modal
          title="选择机构"
          visible={visible}
          onOk={ this.onOk } 
          onCancel={ this.onCancel }
          okText="确定" 
          cancelText="取消"
          wrapClassName="area-input"
        >
          <SelectOrg 
            handleSelect={ this.handleSelect }
          />
        </Modal>
    	</div>
    )
  }
}

module.exports = ModuleName